/*
 *  Copyright (C) 2011 felixtheripper <felixtheripper_AT_gmail.com>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/**
 *
 * @author felixtheripper
 *
 * email: felixtheripper_AT_gmail.com
 * ... please remove "_AT_" from the above string to get the right email address
 *
 */


package org.myorg.ctm.etk.gui.app;



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
import java.util.Vector;
import java.util.logging.Logger;

import org.myorg.ctm.etk.gui.swg.display.choosepass.button.BtnCmdOkAdmin;
import org.myorg.ctm.etk.gui.swg.display.choosepass.FrmChooseAdminLogin;
import org.myorg.ctm.etk.gui.swg.display.login.button.BtnCmdCancelLogin;
import org.myorg.ctm.etk.gui.swg.display.login.button.BtnCmdOkLogin;
import org.myorg.ctm.etk.gui.swg.display.login.FrmLogin;
import org.myorg.ctm.etk.gui.swg.display.firstconfig.button.*;
import org.myorg.ctm.etk.gui.swg.display.firstconfig.FrmFirstConfig;
import org.myorg.ctm.etk.database.app.CurrentDataBaseEtk;
import org.myorg.ctm.etk.database.app.CurrentLoggedUser;
import org.myorg.ctm.etk.gui.swg.action.actioncontroller.ActionController;
import org.myorg.ctm.etk.gui.swg.action.actionmanager.*;
import org.myorg.ctm.etk.gui.swg.display.choosepass.button.BtnCmdCancelAdmin;
import org.myorg.ctm.etk.gui.swg.display.firstconfig.button.BtnDefault;

import org.myorg.ctm.etk.gui.swg.display.frame.FrmPrintableMainEtk;
import org.myorg.shr.gui.swg.lang.IShrObj;
import org.myorg.ctm.etk.gui.swg.display.optionpane.*;
import org.myorg.shr.gui.swg.util.logging.FileHandlerShr;
import org.myorg.ctm.etk.gui.swg.util.property.PrpNamingEtk;
import org.myorg.ctm.etk.gui.swg.util.property.PrpMgrAppli;
import org.myorg.ctm.etk.gui.swg.util.property.PrpMgrUser;
import org.myorg.ctm.etk.gui.swg.util.property.PrpMgrhelpClass2id;
import org.myorg.shr.dtb.action.ActDtbCreateDb;

/**
 *
 * 
 */

//*/
public class AppEtk extends AppAbs implements ActionListener
{

    static
    {
        // pre-requisite
        if (System.getProperty(PrpNamingEtk.STR_PRP_APP_GETTING_STARTED) == null)
        {
                System.err.println("missing property:" + PrpNamingEtk.STR_PRP_APP_GETTING_STARTED +
                         ", exiting");
                System.exit(1);
        }

    }





    public FrmPrintableMainEtk getFrame() { return (FrmPrintableMainEtk) super._frm_; }

    /*
     * memo: order
     * . load actions
     * . create UI
     * . register actions
     **/


    //*/
    public AppEtk() throws Exception
    {
        super(false,false);

        this._vecObj = new Vector<IShrObj>();

        this._acr = new ActionController(this);

        ActionManagerAbs amrManagerAdministrator = new ActionManagerPerspAdministrator(this._acr);
        ActionManagerAbs amrManagerPractitioner = new ActionManagerPerspUserPractitioner(this._acr);
        ActionManagerAbs amrManagerSecretary = new ActionManagerPerspUserSecretary(this._acr);
       

        super._frm_ = new FrmPrintableMainEtk();
        this._frmWelcome_ = new FrmFirstConfig((ActionListener) this);
        this._frmAskAdminPassword_ =  new FrmChooseAdminLogin((ActionListener) this);
        this._frmLogin_ = new FrmLogin((ActionListener) this);

        this._frmAskAdminPassword_.addWindowListener(
            new WindowAdapter(){
                @Override
                public void windowClosing(WindowEvent w){
                    doExit();
                }
            }
        );

        this._frmWelcome_.addWindowListener(
            new WindowAdapter(){
                @Override
                public void windowClosing(WindowEvent w){
                    doExit();
                }
            }
        );

        this._frmLogin_.addWindowListener(
            new WindowAdapter(){
                @Override
                public void windowClosing(WindowEvent w){
                    doExit();
                }
            }
        );

        super._frm_.addWindowListener(
            new WindowAdapter(){
                @Override
                public void windowClosing(WindowEvent w){
                    doExit();
                }
            }
        );

        this._vecObj.add(this._acr);
        this._vecObj.add(amrManagerAdministrator);
        this._vecObj.add(amrManagerPractitioner);
        this._vecObj.add(amrManagerSecretary);
         
    }
//*/
    /**
     * @param args
     */

    //*/
    public static void main(String[] args)
    {
        //-----
        // Catch all the uncaught exceptions
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()
        {
            @Override
            public void uncaughtException(Thread thr, Throwable e)
            {
                System.out.println("Uncaught exception");
                System.err.println("thr.getName()=" + thr.getName());
                e.printStackTrace();
            }
        });
        //-----

        // force the JRE to use english language
        try   {
            String str = System.getProperty(PrpNamingEtk.STR_PRP_APP_LANGUAGE);

            if (str.equalsIgnoreCase("english"))
                    Locale.setDefault(Locale.ENGLISH);
        }  catch(Exception exc) {
                // don't care
        }

        try
        {
            AppEtk appEtk  = null;
                appEtk = new AppEtk();
            

                if (! appEtk.init())  {
                AppEtk._LOGGER_.severe("failed, exiting");
                String strBody = "An error occured, the application will exit.";
                EtkOptionPaneAbs.s_showDialogError(null, strBody);
                System.exit(1);
            }
        } catch(Exception exc) {
            AppEtk._LOGGER_.severe("exc.getMessage()=" + exc.getMessage() + "\n\nexc caught, exiting");
            System.exit(1);
        }
    }

    private void _askAdminPassword_(){

        this._frmAskAdminPassword_.setVisible(true);
    }


    private void _setLastPerspective() throws Exception
    {
        this._frmWelcome_.setVisible(false);
        String strUserLast = PrpMgrUser.s_getUserLast();
        
        if (strUserLast.compareTo(PrpMgrUser.STR_PERSP_ADMINISTRATOR) == 0) // could be in comments, coz called at the end of scope
            this._acr.userPerspectiveAdministratorHandler();
        
        else if(strUserLast.compareTo(PrpMgrUser.STR_PERSP_PRACTITIONER) == 0)
            this._acr.userPerspectivePractitionerHandler();

        else if(strUserLast.compareTo(PrpMgrUser.STR_PERSP_SECRETARY) == 0)
            this._acr.userPerspectiveSecretaryHandler();

        else
        {
            AppEtk._LOGGER_.info("uncaught PropMgrUser.s_getUserLast()=" + PrpMgrUser.s_getUserLast() +
                ", assigning default perspective");

            // using default!
            this._acr.userPerspectiveAdministratorHandler(); // TODO: temporary
        }

        super._frm_.pack();
        super._frm_.setVisible(true);
    }

    private void _welcomeView_(){
        this._frmWelcome_.setVisible(true);
        this._frmWelcome_.setLocationRelativeTo(_frmWelcome_.getParent());
    }

    private void _login_(){
        this._frmLogin_.setVisible(true);
        this._frmLogin_.setLocationRelativeTo(_frmLogin_.getParent());
    }


    @Override
    public boolean init(){
        try {
        if (! super.init())
            return false;

        for (int i=0; i<this._vecObj.size(); i++){
            IShrObj obj = this._vecObj.elementAt(i);
            if (! obj.init())
                return false;
        }
        if (!this._frmAskAdminPassword_.init()){
            return false;
        }
        if (!this._frmLogin_.init()){
            return false;
        }
        if (!this._frmWelcome_.init()){
            return false;
        }

            CurrentLoggedUser.s_getInstance().setUserLogin("root");
            CurrentLoggedUser.s_getInstance().setUserPassword(System.getProperty(PrpNamingEtk.STR_PRP_DTB_ROOT_PASS));
            PrpNamingEtk.s_init();
            PrpMgrAppli.s_init();
            PrpMgrhelpClass2id.s_init();


            if(PrpMgrAppli.s_getConfigPerformed()){
                _login_();
            }
            else{
                _welcomeView_();
            }
       }

       catch (Exception exc) {
            AppEtk._LOGGER_.severe("exc.getMessage()=" + exc.getMessage() + "\n\nexc caught, exiting");
            System.exit(1);
        }
        return true;
    }

    @Override
    public void destroy()
    {
        super.destroy();

        for (int i=0; i<this._vecObj.size(); i++)
        {
            IShrObj obj = this._vecObj.elementAt(i);

            if (obj == null)
                continue;

            obj.destroy();
        }

        PrpMgrAppli.s_destroy();

        this._vecObj.clear();
        this._vecObj = null;
        this._acr = null;
    }


    public void doExit()
    {
        String strTitle = System.getProperty(PrpNamingEtk.STR_PRP_APPLI_TITLE);
        strTitle += " - " + "exit";
        String strBody = "Do you really want to exit?";

        if (! EtkOptionPaneAbs.s_showDialogConfirm(super._frm_, strTitle, strBody))
            return;

        destroy();


        AppEtk._LOGGER_.info(System.getProperty(PrpNamingEtk.STR_PRP_APPLI_TITLE) + " is exiting normally ...");
        System.exit(0);
    }

    public void hidePerspFrame(){
        this._frm_.setVisible(false);
        return;
    }

    public void askLogin(){
        hidePerspFrame();
        this._frmLogin_.setVisible(true);
        return;
    }

    private Vector<IShrObj> _vecObj = null;
    private ActionController _acr = null;


    private FrmFirstConfig _frmWelcome_;
    private FrmChooseAdminLogin _frmAskAdminPassword_;
    private FrmLogin _frmLogin_;


    final static private Logger _LOGGER_ = Logger.getLogger(AppEtk.class.getName());

    static
    {
        AppEtk._LOGGER_.addHandler(FileHandlerShr.s_getInstance());
    }

    public void actionPerformed(ActionEvent e) {

        try{
            if(e.getSource() instanceof BtnManual)
            {
                this._frmWelcome_.setVisible(false);
                _askAdminPassword_();
                return;
            }
            if(e.getSource() instanceof BtnQuick)
            {
                System.out.println("tutu");
                return;
            }
            if(e.getSource() instanceof BtnDefault)
            {
                System.out.println("titi");
                return;
            }
            if(e.getSource() instanceof BtnCmdOkAdmin){
                ActDtbCreateDb.s_getInstance()
                    .doJob(CurrentLoggedUser.s_getInstance().getUserLogin(),
                    CurrentLoggedUser.s_getInstance().getUserPassword(),
                    CurrentDataBaseEtk.getDatabase());
                PrpMgrAppli.s_setConfigPerformed(true);
                this._frmAskAdminPassword_.setVisible(false);
                this._frm_.setVisible(true);
                _setLastPerspective();
                return;
            }
            if(e.getSource() instanceof BtnCmdCancelAdmin){
                destroy();
                System.exit(0);
                return;
            }
            if(e.getSource() instanceof BtnCmdOkLogin){
                String str = this._frmLogin_.getUser();
                PrpMgrUser.s_setUserLast(str);
                //Find mysql login and pass for selected user

                //Logg the user, with CurrentLoggedUser.setUser()
                this._frmLogin_.setVisible(false);
                _setLastPerspective();
                return;
            }
            if(e.getSource() instanceof BtnCmdCancelLogin){
                destroy();
                System.exit(0);
                return;
            }
        }
        catch (Exception exc) {
            exc.printStackTrace();
            AppEtk._LOGGER_.severe("exc.getMessage()=" + exc.getMessage() + "\n\nexc caught, exiting");
            
            
            System.exit(1);
        }
    }
}


